package leetcode.剑指offer.剑指II;

import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/12/13 15:46
 * @description：https://leetcode-cn.com/problems/IDBivT/
 */
public class 剑指_II_85生成匹配的括号 {
    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.generateParenthesis(3));
    }

    class Solution {
        private List<String> ans = new ArrayList<>();
        public List<String> generateParenthesis(int n) {
            // 维护一个balance
            // balance始终为正数且不能超过n
            int balance = 0;
            dfs(balance, n, new StringBuilder());
            return ans;
        }

        private void dfs(int balance, int n, StringBuilder builder) {
            if (builder.length() == n * 2) {
                if (balance == 0) {
                    ans.add(builder.toString());
                }
                return;
            }
            // 拿(
            if (balance < n) {
                dfs(balance + 1, n, new StringBuilder(builder).append("("));
            }

            // 拿）
            if (balance > 0) {
                dfs(balance - 1, n , new StringBuilder(builder).append(")"));
            }
        }
    }
}
